package com.crdeng.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crdeng.business.entity.*;
import com.crdeng.business.mapper.InStockInfoMapper;
import com.crdeng.business.mapper.InStockMapper;
import com.crdeng.business.mapper.ProductStockMapper;
import com.crdeng.business.service.InStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crdeng.business.service.ProductService;
import com.crdeng.business.service.SupplierService;
import com.crdeng.business.vo.*;
import com.crdeng.handler.BusinessException;
import com.crdeng.response.ResultCode;
import com.crdeng.system.vo.UserRoleVO;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author crdeng
 * @since 2021-01-03
 */
@Transactional
@Service
public class InStockServiceImpl extends ServiceImpl<InStockMapper, InStock> implements InStockService {

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ProductService productService;

    @Autowired
    private InStockInfoMapper inStockInfoMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Override
    public IPage<InStockVO> findInStockPage(IPage<InStockVO> page, InStockQueryMapVO queryMap) {
        QueryWrapper<InStockVO> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(queryMap.getStatus())){
            queryWrapper.eq("stock.status",queryMap.getStatus());
        }

        if (!StringUtils.isEmpty(queryMap.getType())){
            queryWrapper.eq("stock.type",queryMap.getType());
        }

        if (!StringUtils.isEmpty(queryMap.getInNum())){
            queryWrapper.like("stock.in_num",queryMap.getInNum());
        }

        if (queryMap.getStartTime()!=null&&queryMap.getEndTime()!=null){
            queryWrapper.ge("stock.create_time",queryMap.getStartTime());
            queryWrapper.le("stock.modified",queryMap.getEndTime());
        }

        queryWrapper.orderByDesc("stock.create_time");
        queryWrapper.ne("stock.status",1);

        return baseMapper.findInStockPage(page,queryWrapper);
    }


    @Override
    public InStockDetailVO getDetail(Long id,Integer current, Integer size) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();

        InStock inStock = getById(id);
        if (inStock==null) throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(),"入库单不存在");
        BeanUtils.copyProperties(inStock,inStockDetailVO);
        Supplier supplier = supplierService.getById(inStock.getSupplierId());
        if (inStock!=null){
            inStockDetailVO.setSupplier(supplier);
        }else {
            throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(),"供应商不存在");
        }

        Page<InStockItemVO> inStockItemVOPage = new Page<>(current,size);
        QueryWrapper<InStockItemVO> inStockItemVOQueryWrapper = new QueryWrapper<>();
        inStockItemVOQueryWrapper.eq("in_num",inStock.getInNum());
        IPage<InStockItemVO> stockInfo = baseMapper.getStockInfo(inStockItemVOPage, inStockItemVOQueryWrapper);
        List<InStockItemVO> inStockItemVOList = stockInfo.getRecords();
        inStockDetailVO.setTotal(stockInfo.getTotal());


        for (InStockItemVO inStockItemVO : inStockItemVOList) {
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("p_num",inStockItemVO.getPNum());
            Product product = productService.getOne(queryWrapper);
            if (product!=null){
                inStockItemVO.setModel(product.getModel());
                inStockItemVO.setImageUrl(product.getImageUrl());
                inStockItemVO.setName(product.getName());
                inStockItemVO.setUnit(product.getUnit());
            }else {
                throw new BusinessException(ResultCode.PARAM_NOT_VALID.getCode(),"物资不存在");
            }
        }
        inStockDetailVO.setItemVOS(inStockItemVOList);

        return inStockDetailVO;
    }

    /**
     * 添加入库单
     * @param addInStockVO
     */
    @Override
    public void add(AddInStockVO addInStockVO) {
        //生成订单号
        String IN_STOCK_NUM = UUID.randomUUID().toString().substring(0, 32).replace("-", "");
        //记录入库商品的总数
        int itemNumber=0;
        List<Object> products = addInStockVO.getProducts();
        if (!CollectionUtils.isEmpty(products)){
            for (Object product : products) {
                LinkedHashMap item = (LinkedHashMap) product;
                System.out.println(product.toString());
                int productNumber = (int) item.get("productNumber");
                Integer productId = (Integer) item.get("productId");
                Product dbProduct = productService.getById(productId);
                if (dbProduct==null){
                    throw new BusinessException(ResultCode.COMMON_FAIL.getCode(),"商品不存在");
                }else if (dbProduct.getStatus()==1){
                    throw new BusinessException(ResultCode.COMMON_FAIL.getCode(),dbProduct.getName()+"物资已被回收,无法入库");
                }else if(dbProduct.getStatus()==2){
                    throw new BusinessException(ResultCode.COMMON_FAIL.getCode(),dbProduct.getName()+"物资待审核,无法入库");
                }else if (productNumber<=0){
                    throw new BusinessException(ResultCode.COMMON_FAIL.getCode(),dbProduct.getName()+"入库数量不合法,无法入库");
                }else {
                    itemNumber+=productNumber;
                    InStockInfo inStockInfo = new InStockInfo();
                    Date date = new Date();
                    inStockInfo.setCreateTime(date);
                    inStockInfo.setModifiedTime(date);
                    inStockInfo.setProductNumber(productNumber);
                    inStockInfo.setPNum(dbProduct.getPNum());
                    inStockInfo.setInNum(IN_STOCK_NUM);
                    inStockInfoMapper.insert(inStockInfo);
                    QueryWrapper<ProductStock> productStockQueryWrapper = new QueryWrapper<>();
                    productStockQueryWrapper.eq("p_num",dbProduct.getPNum());
                    ProductStock productStock = productStockMapper.selectOne(productStockQueryWrapper);
                    productStock.setStock(productStock.getStock()+productNumber);
                    productStockMapper.updateById(productStock);
                }

            }

            InStock inStock = new InStock();
            BeanUtils.copyProperties(addInStockVO,inStock);
            inStock.setInNum(IN_STOCK_NUM);//单号
            Date date = new Date();
            inStock.setCreateTime(date);
            inStock.setModified(date);
            inStock.setProductNumber(itemNumber);
            /*获取当前登录用户*/
            UserRoleVO userRoleVO = (UserRoleVO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            inStock.setOperator(userRoleVO.getUsername());
            //设置为待审核
            inStock.setStatus(2);
            save(inStock);


        }else {
            throw new BusinessException(ResultCode.PARAM_IS_BLANK.getCode(),"入库商品不能为空");
        }
    }

    /**
     * 改变入库单的状态
     * @param id
     * @param statusNum
     */
    @Override
    public void alterStatus(Long id,Integer statusNum) {
        InStock byId = getById(id);
        if (byId==null){
            throw new BusinessException(ResultCode.COMMON_FAIL.getCode(),"入库单不存在");
        }
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock.setStatus(statusNum);
        updateById(inStock);
    }
}
